/*
    3.conncector.c 建立终端进行并发操作
*/

/*
    支持多个终端连接并发执行
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <fcntl.h>

#include "sharedspace.h"



int main(int argc, char *argv[])
{
    void *shmptr = NULL;

    struct shared_space *shared;
    //struct shared_struct *shared;

    int shmid;
    key_t key;
    //-------------------------从路径名生成IPC_KEY
    struct stat fileattr;

    char pathname[80], key_str[10], cmd_str[80];
    int ret;
    if(argc <2) {
        printf("Usage: ./a.out pathname\n");
        return EXIT_FAILURE;
    }
    strcpy(pathname, argv[1]);

    if(stat(pathname, &fileattr) == -1) {
        //if don't insist then create a file;
        ret = creat(pathname, O_RDWR);
        if (ret == -1) {
            ERR_EXIT("creat()");
        }
        printf("shared file object created\n");
    }
 
    key = ftok(pathname, 0x27); /* 0x27 a project ID 0x0001 - 0xffff, 8 least bits used */
    if(key == -1) {
        ERR_EXIT("shmcon: ftok()");
    }
    //---------------
    //get key from parent process

    printf("%*sshmread: IPC key = %x\n", 30, " ", key);
    
    shmid = shmget((key_t)key, sizeof(struct shared_space), 0666|PERM);
    if (shmid == -1) {
        ERR_EXIT("shread: shmget()");
    }

    shmptr = shmat(shmid, 0, 0);
    if(shmptr == (void *)-1) {
        ERR_EXIT("shread: shmat()");
    }
    printf("%*sshmread: shmid = %d\n", 30, " ", shmid);    
    printf("%*sshmread: shared memory attached at %p\n", 30, " ", shmptr);
    printf("%*sshmread process ready ...\n", 30, " ");
    sprintf(cmd_str, "ipcs -m | grep '%d'\n", shmid); 
    printf("\n------ Shared Memory Segments ------\n");
    system(cmd_str);
    
    sleep(2);
    shared = (struct shared_space*)shmptr;
    StaticLinkList* list_ptr = &shared->L;\
    showOperation();

    while (1)
    {
        printf(">>>");
        char choice;
        scanf("%c",&choice);
        makeDecision(shared,choice);

    }
    
   if (shmdt(shmptr) == -1) {
        ERR_EXIT("shmread: shmdt()");
   }
 
    sleep(1);
    exit(EXIT_SUCCESS);
}


